package com.itqf.proxy.dynimic_cglib.factory;

import com.itqf.proxy.dynimic_cglib.MyAdvisor;
import com.itqf.proxy.dynimic_cglib.impl.ProductServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

/**
 * @Description:  cglib实现动态代理
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/9/28
 * @Time: 下午5:20
 */

public class MyServiceProxyFactory {


    public  static ProductServiceImpl createProxyService(){
       //1,创建被代理对象  可以没有接口
        ProductServiceImpl impl = new ProductServiceImpl();
        //2,创建字节码增强的核心对象
        Enhancer enhancer = new Enhancer();
        //3,设置被代理对象为超类
        enhancer.setSuperclass(impl.getClass());
        //4,设置一个回调方法  执行器
        //创建增强类对象
        MyAdvisor myAdvisor = new MyAdvisor();
        enhancer.setCallback(new InvocationHandler() {//CallBack实现类  InvocationHandler  MethodInteceptor
            @Override
            public Object invoke(Object proxy, Method method, Object[] objects) throws Throwable {
                myAdvisor.before();
                try {
                    Object result = method.invoke(impl, objects);
                    myAdvisor.after();

                    return result;
                }catch (Exception e){
                    myAdvisor.throwsAfter();
                }
               return  null;
            }
        });

        //5.创建代理对象
       return (ProductServiceImpl) enhancer.create();


    }


}
